import React, { useEffect, useRef, useState } from "react";
import { Modal, Form, Input, Radio, Select, Button, Row, Col, InputRef } from "antd";
import CloseOutlined from "@ant-design/icons/lib/icons/CloseOutlined";
import {   PostConfig, ConfigData } from "../../types"; // 从上上层目录导入
import { postConfig, publishConfig, queryConfig, queryPreviewConfig, tryMsg, useGetEnvironments, useGetProjects } from "../../service";
const { TextArea } = Input;


interface ConfigAddProps {
    visible: boolean;
    projectId?: number;
    envId?: number;
    onClose: () => void;
    onFlush?: (flush: boolean) => void;

    
  }
  
  interface FormData {
      projectId: number
      environmentId: number,
      dependencyProjectIds:Array<number>,
      content: string,
  } 
  
 

const ConfigAdd: React.FC<ConfigAddProps> = ({ projectId,envId,visible, onClose,onFlush }) => {
  const [form] = Form.useForm<PostConfig>();

  // 获取项目数据
  const { projects, projectsLoading,loadProjects } = useGetProjects({});

  const { environments, environmentsLoading,loadEnv } = useGetEnvironments({});
  
  const [openPreview,setOpenPreview] = useState<boolean>(false);
  const [previewConfig,setPreviewConfig] = useState<string>('');
  const [configData,setConfigData] = useState<ConfigData|null>(null);
  const reasonInputRef = useRef<InputRef>();
  const [reason,setReason] = useState<string>('')
  const handleOk = () => {
    form.validateFields().then(async (values:PostConfig) => {

        await tryMsg(async()=>{
            await postConfig(values)
            onFlush(true)
        })

    });
  };
  useEffect(()=>{
      queryConfig({projectId:projectId,environmentId:envId}).then(x=>{
          setConfigData(x.data)
      })
  },[
    projectId,envId
  ])
  
  const handleCancel = () => {
    form.resetFields();
    onClose();
  };
  useEffect(()=>{
      form.setFieldsValue({
          content:configData?.content,
          dependencyProjectIds:configData?.dependencyProjectIds
      })
  },[configData])

  // 输入过滤逻辑
  const filterOption = (input: string, option: any) => {
    return (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
  };
  let initForm = {}
  initForm = {
      projectId: projectId,
      environmentId: envId,
      content: configData?.content,
      dependencyProjectIds:configData?.dependencyProjectIds?configData.dependencyProjectIds:[-1]
  }

  console.log("initForm",configData, initForm)
  const handlePreview = async ()=>{
    let projectId = form.getFieldValue("projectId")
    let envId = form.getFieldValue("environmentId")
    
    let rsp = await queryPreviewConfig({projectId:projectId,environmentId:envId})
    let config = rsp.data.content;
    console.log("preview config",config)
    setPreviewConfig(config);
    setOpenPreview(true)

    
  }
  const handleConfirm = () => {
      Modal.confirm({
        title: '请输入原因',
        content: (
          <Input
           ref={reasonInputRef}
            placeholder="请输入原因"
            onChange={(e) => setReason(e.target.value)}
          />
        ),
        onOk: () => {

            tryMsg(async()=>{
                return await publishConfig({
                    projectId: projectId, environmentId: envId, content: previewConfig,
                    memo: reasonInputRef?.current?.input.value
                });
            })
        },
        onCancel: () => {
          console.log('取消操作');
        },
      });
    };
  const handlerPub = handleConfirm

  return (
    <Modal
      title="新建配置"
      open={visible}
      key={projectId+envId}
      destroyOnClose={true}
      onCancel={handleCancel}
      footer={[
        <Button key="cancel" onClick={handleCancel}>
          取消
        </Button>,
             <Button key="preview" color="cyan" variant="solid" onClick={handlePreview}>
             预览已提交配置
           </Button>,
        <Button key="submit" type="primary" onClick={handleOk}>
          提交
        </Button>,
      ]}
      closeIcon={<CloseOutlined />}
      width={1000} // 增加对话框宽度
    >
      <Modal title="预览配置" open={openPreview}   width={1000} onClose={()=>{
          setOpenPreview(false)
      }} onCancel={()=>{
        setOpenPreview(false)
      }} closeIcon={<CloseOutlined />} footer={[
        <Button key="cancel" onClick={()=>{
          setOpenPreview(false)
        }}>
          取消
        </Button>,
         
        <Button key="submit" type="primary" onClick={handlerPub}>
          发布
        </Button>,
      ]} >
        <pre>
          <TextArea rows={previewConfig.split("\n").length + 2} value={previewConfig}>

          </TextArea>
        </pre>
      </Modal> 
      <Form form={form} layout="vertical" initialValues={initForm}>
        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              name="projectId"
              
              label="项目"
              rules={[{ required: true, message: "请选择项目" }]}
            >
              <Select
                placeholder="请选择项目"
                showSearch
                disabled={projectsLoading}
                loading={projectsLoading}
                filterOption={filterOption}
                options={projects && projects?.map((project) => ({
                  label: `${project.description}(${project.name})` ,
                  value: project.id,
                }))}
              />
            </Form.Item>

            <Form.Item
              name="environmentId"
              label="环境列表"
              rules={[{ required: true, message: "请选择环境" }]}
            >
              <Select
                placeholder="请选择环境"
                showSearch
                disabled={environmentsLoading}
                filterOption={filterOption}

                loading={environmentsLoading}
                 options={environments?.map((project) => ({
                    label: `${project.description}(${project.name})` ,
                  value: project.id,
                }))}
              />
                  
            </Form.Item>

            <Form.Item
              name="dependencyProjectIds"
              label="依赖项目"
            >
              <Select
                mode="multiple"
                placeholder="请选择依赖项目"
                filterOption={filterOption}
                options={projects && projects?.map((project) => ({
                    label: `${project.description}(${project.name})` ,
                  value: project.id,
                }))}
              >
                {/* {projects?.map(project => (
                  <Select.Option key={project.name} value={project.id}>
                    {project.description}({project.name})
                  </Select.Option>
                ))} */}
             
              </Select>
            </Form.Item>
          </Col>
          <Col span={16}>
            <Form.Item
              name="content"
              label="配置内容"
              rules={[{ required: true, message: "请输入配置内容" }]}
            >
              <TextArea rows={25} placeholder="请输入配置内容" />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

export default ConfigAdd;